$ErrorActionPreference = 'Stop'

Write-Host '🔧 正在自动配置 Python 到 PATH...'

$commonPaths = @(
  "$env:LOCALAPPDATA\Programs\Python\Python313",
  "$env:LOCALAPPDATA\Programs\Python\Python312",
  "C:\\Python313",
  "C:\\Python312",
  "C:\\Program Files\\Python313",
  "C:\\Program Files\\Python312"
)

$found = $null
foreach ($p in $commonPaths) {
  if (Test-Path (Join-Path $p 'python.exe')) {
    $found = $p
    break
  }
}

if (-not $found) {
  Write-Host '❌ 未找到Python安装目录，请确认已安装（或重装并勾选 Add Python to PATH）'
  exit 1
}

# 更新当前会话 PATH
$env:PATH = "$env:PATH;$found;$found\Scripts"

# 更新用户 PATH（无需管理员）
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
if (-not $userPath) { $userPath = '' }
if ($userPath -notlike "*$found*") {
  $newUserPath = ($userPath.TrimEnd(';')) + ";$found;$found\Scripts"
  [Environment]::SetEnvironmentVariable('Path', $newUserPath, 'User')
  Write-Host "✅ 已将 $found 和 Scripts 写入用户 PATH"
} else {
  Write-Host '✅ 用户 PATH 已包含 Python 路径'
}

# 打印验证信息
Write-Host '🔎 验证 Python 版本:'
& "$found\python.exe" --version

Write-Host '🔎 验证 pip 版本:'
try {
  & "$found\python.exe" -m pip --version
} catch {
  Write-Host '⚠️ 未检测到 pip，尝试引导安装...'
  & "$found\python.exe" -m ensurepip -U
  & "$found\python.exe" -m pip --version
}

Write-Host '🎉 Python 环境变量配置完成（当前会话已生效，用户 PATH 已更新）' 